package com.zny.sescore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.palmdoctor.mb.base.rule.constant.ItemSourceEnum;
import com.zny.sescore.annotation.ItemSource;
import com.zny.sescore.dao.AssessRecordDao;
import com.zny.sescore.engine.AssessRuleEngine;
import com.zny.sescore.exception.BizException;
import com.zny.sescore.exception.MessageEnum;
import com.zny.sescore.model.AssessModelItem;
import com.zny.sescore.model.AssessModelResult;
import com.zny.sescore.model.AssessRecord;
import com.zny.sescore.model.vo.AssessModelVO;
import com.zny.sescore.model.vo.AssessRecordVO;
import com.zny.sescore.service.AssessModelResultService;
import com.zny.sescore.service.AssessModelService;
import com.zny.sescore.service.AssessRecordService;
import com.zny.sescore.annotation.SourceHandler;
import com.zny.sescore.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 患者评估结果service
 */
@Slf4j
@Service
public class AssessRecordServiceImpl extends ServiceImpl<AssessRecordDao, AssessRecord> implements AssessRecordService {

    @Autowired
    private AssessRuleEngine ruleEngine;

    @Autowired
    private AssessModelService modelService;

    @Autowired
    private List<SourceHandler> sourceHandlerList;

    @Autowired
    private AssessModelService assessModelService;

    @Autowired
    private AssessModelResultService resultService;

    @Override
    public AssessModelResult submitPatientAssessResult(AssessRecordVO recordVO) {

        // 获取model信息
        AssessModelVO modelVO = modelService.getAssessModelVO(recordVO.getModelId());

        // 查询非页面输入所有项目
        Map<String, List<AssessModelItem>> sourceFieldMap = modelVO.getItemList()
                .stream()
                .filter(item -> StringUtils.isNotEmpty(item.getItemSource())
                        && !Objects.equals(item.getItemSource(), ItemSourceEnum.INPUT.getCode()))
                .collect(Collectors.groupingBy(AssessModelItem::getItemSource));

        // 查询费页面输入分类值
        Map<String, Object> sourceValueMap = new HashMap<>();
        sourceFieldMap.forEach((key, value) -> {
            log.info("疾病评估获取元数据 key={}", key);
            SourceHandler sourceHandler = getSourceHandler(ItemSourceEnum.getByCode(key));
            List<String> categoryNameList = new ArrayList<>();
            if (Objects.equals(key, ItemSourceEnum.LIS.getCode())) {
                categoryNameList.addAll(
                        value.stream()
                                .map(AssessModelItem::getSourceCategory2)
                                .collect(Collectors.toList())
                );
            } else {
                categoryNameList.addAll(
                        value.stream()
                                .map(AssessModelItem::getSourceCategory1)
                                .collect(Collectors.toList())
                );
            }
            sourceValueMap.putAll(sourceHandler.getSourceValue(recordVO.getPatientId(), recordVO.getJzlsh(), categoryNameList));
        });

        // 给非页面输入项目取值
        modelVO.getItemList().forEach(item -> {
            if (Objects.equals(item.getItemSource(), ItemSourceEnum.PACS.getCode())
                    || Objects.equals(item.getItemSource(), ItemSourceEnum.PATIENT_INO.getCode())) {
                recordVO.getValueMap().put(item.getItemCode(), sourceValueMap.get(item.getSourceCategory1()));
            } else if (Objects.equals(item.getItemSource(), ItemSourceEnum.LIS.getCode())) {
                recordVO.getValueMap().put(item.getItemCode(), sourceValueMap.get(item.getSourceCategory2()));
            }
        });

        AssessModelResult modelResult = ruleEngine.eval(modelVO, recordVO.getValueMap());
        saveAssessRecord(recordVO, modelResult);
        return modelResult;
    }

    @Override
    public List<AssessRecord> getPatientResultDetail(int modelId, int diseaseId, int patientId) {
        AssessRecord resultQuery = new AssessRecord();
        resultQuery.setModelId(modelId);
        resultQuery.setPatientId(patientId);
        resultQuery.setDiseaseId(diseaseId);
        return list(new QueryWrapper<>(resultQuery));
    }



    public void saveAssessRecord(AssessRecordVO record, AssessModelResult result) {
        AssessModelVO model = assessModelService.getAssessModelVO(record.getModelId());
        record.setResultId(result.getResultId());
        record.setCustomValue(result.getCustomValue());
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("model", model);
        jsonMap.put("valueMap", record.getValueMap());
        record.setRecordJson(JsonUtil.objectToString(jsonMap));
        save(record);
    }

    private SourceHandler getSourceHandler(ItemSourceEnum sourceEnum) {
        return sourceHandlerList.stream()
                .filter(handler -> handler.getClass().getAnnotation(ItemSource.class).value() == sourceEnum)
                .findFirst()
                .orElseThrow(() -> new BizException(MessageEnum.ASSESS_CONFIG_ERROR));
    }
}




